import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';
import {OrderAccDetailsService} from './order-acc-details.service';
import {HomeComponent} from '../../home/home.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {Location as Location1} from '@angular/common';
import {defalutImg} from 'src/app/comm';
import {CommonService} from '../../../services-common/common.service';
import {PermissionService} from '../../../service/permission.service';

@Component({
  selector: 'app-order-acc-details',
  templateUrl: './order-acc-details.component.html',
  styleUrls: ['./order-acc-details.component.scss']
})

export class OrderAccDetailsComponent implements OnInit {

  @ViewChild('appFollowComponent') appFollowComponent: any;
  id: any = null;
  deadline = Date.now() + 1000 * 60 * 60 * 24 * 2 + 1000 * 30;
  refundVisible: any = false;
  affirmVisible: any = false;
  extendTimeVisible: boolean = false;
  modifyPriceVisible: boolean = false;
  /**
   * 跟进模态框
   */
  followVisible: boolean = false;
  /**
   * 详情数据
   */
  detailsData: any = null;
  /**
   * 全局 loading
   */
  messageId: any = null;
  /**
   * 确认退款文字
   */
  affirmText: string = '';
  /**
   * 跟进内容
   */
  followList: any = [];
  /**
   * 参数
   */
  entityParam: any = {
    id: null,
    // 退款金额
    refundPrice: null,
    // 我方承担运费
    bearFreight: null,
    // 延长日期
    afterSaleCloseTime: null
  };
  /**
   * 改价
   */
  modifyPriceParam: any = {
    id: 0,
    // 优惠邮费
    favorablePostage: null,
    // 改价金额
    priceChange: null,
  };
  /**
   * 跟进参数
   */
  followParam: any = {
    // 关联信息(订单号 售后单号 客户id 出库单号)
    relationInformation: '',
    // 1、订单 2、售后 3、客户 4、出库
    type: 1,
    // 文件列表
    enclosure: [],
    // 备注
    content: '',
  };
  /**
   * 购买数量
   */
  numSum: number = 0;
  /**
   * 小计
   */
  subTotal: number = 0;
  /**
   * 优惠小计
   */
  favorablePriceSum: number = 0;
  /**
   * 上传val
   */
  inputVal: any = null;
  // 售后状态
  statusSet: any = {0: '用户提交申请（待审核）', 1: '审核通过（待买家退货）', 2: '退货超时', 3: '商品已寄出', 4: '待平台审核', 5: '直接退款', 6: '售后成功', 7: '售后失败', 8: '已取消'};
  // 临时缓存数据
  cecheData: any = {
    // 总金额
    tatalCount: 0
  };

  /**
   * 加载失败显示图像占位符
   */
  fallback: string = defalutImg;
  // 渠道list
  channelSelects: any = [];

  // 订单取消loading
  cancelLoading: boolean = false;

  // 对公转账信息Modal
  transferVisible = false;
  transferInfo: any = null;
  subsidyStatus: Array<string> = [
    '待生成', '待打款', '打款完成', '打款失败'
  ];

  // 补贴规则
  subsidyRuleList: Array<any> = [];

  constructor(
    private HomeComponent: HomeComponent,
    private router: Router,
    private message: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private OrderAccDetailsService: OrderAccDetailsService,
    private location: Location1,
    private modal: NzModalService,
    private commonService: CommonService,
    public permissionService: PermissionService
  ) {
  }

  ngOnInit(): void {
    this.getChannelData(); // 渠道
    this.HomeComponent.scrollTopZero();

    this.activatedRoute.params.subscribe(params => {
      this.id = params.id;
      this.entityParam.id = params.id;
      this.modifyPriceParam.id = params.id;
    });
    this.getDetails();
  }

  /**
   * 跳转商品详情
   */
  toGoodsInfo(goodsId: any) {
    this.router.navigate(['goods/goodsTabs', goodsId]);
  }

  getDetails() {
    this.OrderAccDetailsService.getDetails(this.id).subscribe((res: any) => {
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.detailsData = res.data;
      for (let index = 0; index < this.detailsData.orderExpress.length; index++) {
        const element = this.detailsData.orderExpress[index];
        element.expressTraces = element.expressTraces ? JSON.parse(element.expressTraces) : [];
      }
      this.detailsData.order.statusText = this.status_To_Text(this.detailsData.order.status);

      // 合计
      for (let index = 0; index < this.detailsData.order.list.length; index++) {
        const element = this.detailsData.order.list[index];
        for (let index = 0; index < element.list.length; index++) {
          const element1 = element.list[index];
          this.numSum += element1.num;
          this.subTotal += (element1.num * element1.price);
          this.favorablePriceSum += element1.favorablePrice;
        }
      }
      //  退款成功总额
      this.detailsData?.orderRefunds?.forEach((element: any) => {
        this.cecheData.tatalCount += element.refundPrice;
      });

      // 对公转账
      this.transferInfo = this.detailsData.order.transferInfo ? JSON.parse(this.detailsData.order.transferInfo) : null;

      // 补贴规则
      this.subsidyRuleList = res.data.renewalRule ? JSON.parse(res.data.renewalRule) : [];
    }, err => {
      this.createMessage('error', err.message);
    });
  }

  /**
   * 退款状态转文字
   */
  refundState_To_Text(s: any) {
    let test = '';
    switch (s) {
      case 0:
        test = '未付款';
        break;
      case 1:
        test = '已付款';
        break;
      case 2:
        test = '部分退款';
        break;
      case 3:
        test = '全部退款';
        break;
      default:
        test = '-';
        break;
    }
    return test;
  }

  /**
   * 支付状态转文字
   */
  payType_To_Text(s: any) {
    let test = '';
    switch (s) {
      case 1:
        test = '支付宝';
        break;
      case 2:
        test = '微信';
        break;
      case 3:
        test = '银联';
        break;
      default:
        test = '-';
        break;
    }
    return test;
  }

  /**
   * 状态转文字
   */
  status_To_Text(s: any) {
    let test = '';

    switch (s) {
      case 0:
        test = '有效';
        break;
      case 1:
        test = '无效';
        break;
      case 2:
        test = '待付款';
        break;
      case 3:
        test = '待审核';
        break;
      case 4:
        test = '审核不通过';
        break;
      case 5:
        test = '审核通过';
        break;
      case 6:
        test = '排队发货';
        break;
      case 7:
        test = '待发货';
        break;
      case 8:
        test = '待收货（已发货）';
        break;
      case 9:
        test = '交易完成';
        break;
      case 10:
        test = '支付超时';
        break;
      case 11:
        test = '客服取消';
        break;
      case 12:
        test = '客户取消';
        break;
      case 13:
        test = '售后中';
        break;
      case 14:
        test = '全部退货';
        break;
      default:
        test = '-';
        break;
    }
    return test;
  }

  /**
   * 物流编码转文字
   */
  expressCode_To_Text(s: any) {
    let test = '';
    switch (s) {
      case 'SF':
        test = '顺丰';
        break;
      case 'YTO':
        test = '圆通';
        break;
      case 'ZTO':
        test = '中通';
        break;
      case 'STO':
        test = '申通';
        break;
      case 'YD':
        test = '韵达';
        break;
      case 'JD':
        test = '京东';
        break;
      default:
        test = '-';
        break;
    }
    return test;
  }

  // 售后 状态
  saleStatic_to_text(val: any) {
    return this.statusSet[val] || '-';
  }

  /**
   * 文件上传完成回调
   * @param files
   * @param type  1:图片信息 2:视频文件 3:视频封面
   */
  handleFileInput(files: any, type: any) {
    let fileArr = files.target.files;
    for (let index = 0; index < fileArr.length; index++) {
      const element = fileArr[index];
      this.postFile(element, this.splitFileName(element.name), (res: any) => {
        if (res.code != 0) {
          return;
        }
        // 上传类型
        if (type == 2) {
          this.followParam.enclosure.push({
            // 显示地址
            showUrl: element.name,
            // 图片地址
            url: res.data,
          });
        }
        this.inputVal = null;
      });
    }
  }

  /**
   * 跟进查询
   */
  followerLst() {
    if (this.messageId != null) {
      return;
    }
    this.createBasicMessage();
    this.OrderAccDetailsService.followerLst(this.followParam).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.followVisible = true;
      this.followList = res.data;
      for (let index = 0; index < this.followList.length; index++) {
        let element = this.followList[index];
        element.enclosure = element.enclosure ? element.enclosure.split(',') : [];
      }
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 确认退款
   */
  confirmRefund() {
    if (this.messageId != null) {
      return;
    }

    if (!this.affirmText) {
      return this.createMessage('warning', '请输入“确认退款”文字');
    }
    if (this.affirmText != '确认退款') {
      return this.createMessage('warning', '请输入“确认退款”文字');
    } else {
      this.createBasicMessage();
      this.OrderAccDetailsService.update(this.entityParam).subscribe((res: any) => {
        this.removeBasicMessage();
        if (res.code != 0) {
          this.createMessage('error', res.message);
          return;
        }
        this.createMessage('success', '退款成功');
        this.handleCancel();
        this.affirmCancel();
        this.getDetails();
      }, err => {
        this.removeBasicMessage();
        this.createMessage('error', err.message);
      });
    }
  }

  /**
   * 售后延期确认
   * @returns
   */
  extendTimeConfirm() {
    if (this.messageId != null) {
      return;
    }
    if (!this.entityParam.afterSaleCloseTime) {
      return this.createMessage('warning', '请选择延长售后日期');
    }
    this.createBasicMessage();
    this.OrderAccDetailsService.update(this.entityParam).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', '售后延期成功');
      this.handleCancel();
      this.getDetails();
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 改价
   */
  modifyPriceConfirm() {
    if (this.messageId != null) {
      return;
    }
    // if (!this.modifyPriceParam.favorablePostage) {
    //     return this.createMessage("warning", "请输入邮费优惠额度");
    // }
    if (!this.modifyPriceParam.priceChange) {
      return this.createMessage('warning', '请输入订单优惠额度');
    }
    this.createBasicMessage();
    this.OrderAccDetailsService.modifyPrice(this.modifyPriceParam).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', '改价成功');
      this.handleCancel();
      this.getDetails();
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 新增跟进
   */
  followerSave() {
    const {type} = this.followParam;
    if (this.messageId != null) {
      return;
    }
    if (!this.followParam.content) {
      return this.createMessage('warning', '请输入备注');
    }
    this.createBasicMessage();
    this.OrderAccDetailsService.followerSave(this.followParam).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      type == 1 && this.appFollowComponent.httpFollowList(); //刷新跟进列表
      this.handleCancel();
      this.createMessage('success', '跟进信息成功');
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 只保留文件名加后缀
   */
  formUrl(url: String) {
    return url.substr(url.lastIndexOf('/') + 1);
  }

  /**
   * 删除跟进图片
   */
  deleteFollowImg(index: any) {
    this.inputVal = null;
    this.followParam.enclosure = this.followParam.enclosure.filter((item: any, i: any) => {
      return i != index;
    });
  }

  /**
   * 打开模态框(跟进) 初始化
   * @param id
   */
  followModal(relationInformation: any, type: any): void {
    this.followParam.relationInformation = '';
    this.followParam.relationInformation = relationInformation;
    this.followParam.type = type;
    this.followVisible = true;
  }

  /**
   * 打开模态框(订单改价) 初始化
   * @param id
   */
  modifyPriceModal() {
    this.modifyPriceVisible = true;
  }

  /**
   * 打开模态框(售后延期) 初始化
   * @param id
   */
  extendTimeModal() {
    this.extendTimeVisible = true;
  }

  /**
   * 打开模态框(售后退款) 初始化
   * @param id
   */
  showModal(): void {
    this.refundVisible = true;
  }

  /**
   * 打开模态框(确认退款) 初始化
   * @param id
   */
  affirmModal(): void {
    if (!this.entityParam.refundPrice) {
      return this.createMessage('warning', '退款金额不能为空');
    }
    if (this.entityParam.bearFreight === null || this.entityParam.bearFreight === '') {
      return this.createMessage('warning', '我方承担运费不能为空');
    }
    this.affirmVisible = true;
  }

  /**
   * 模态框关闭触发
   */
  handleCancel(): void {
    this.refundVisible = false;
    this.extendTimeVisible = false;
    this.modifyPriceVisible = false;
    this.followVisible = false;

    this.affirmText = '';

    this.entityParam.refundPrice = null;
    this.entityParam.bearFreight = null;
    this.entityParam.afterSaleCloseTime = null;

    this.modifyPriceParam.favorablePostage = null;
    this.modifyPriceParam.priceChange = null;

    this.followParam.content = '';
    this.followParam.enclosure = [];
  }

  /**
   * 上传文件
   * @param su 上传完成回调函数
   */
  postFile(file: any, fileName: string, su: any) {
    this.OrderAccDetailsService.postFile(file, fileName).subscribe(data => {
      if (su) {
        su(data);
      }
    }, error => {

    });
  }

  // 获取渠道（字典）
  async getChannelData() {
    try {
      const res: any = await this.OrderAccDetailsService.dictData('channel');
      this.channelSelects = res.data.list.records || [];
    } catch {
      // console.log('errro')
    }
  }

  /**
   * 模态框关闭触发(确认退款)
   */
  affirmCancel() {
    this.affirmVisible = false;
  }

  /**
   * 取消订单
   */
  cannelOrderModal(id: any) {
    this.modal.confirm({
      nzTitle: '取消订单',
      nzContent: '<b style="color: red;">确认取消？该操作不可逆，请提前和用户沟通</b>',
      nzOkText: '是',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        if (id) {
          this.cancelLoading = true;
          this.OrderAccDetailsService.cancelOrderData({orderId: id}).subscribe((res: any) => {
            this.cancelLoading = false;
            if (res.code == 0) {
              this.message.success('取消成功');
              // this.location.back();
              this.getDetails();
            } else {
              this.message.error(res.message || '取消失败');
            }
          }, error => {
            this.cancelLoading = false;
            this.message.error(error || '取消失败');
          });
        }
      },
      nzCancelText: '否',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  /**
   * 状态转换颜色
   */
  getStatusColor(s: any) {
    let colorText = '';
    switch (parseInt(s)) {
      // 红色
      case 2:
      case 10:
      case 11:
      case 12:
      case 14:
        colorText = 'font2';
        break;
      // 橙色
      case 3:
      case 6:
      case 13:
        colorText = 'font3';
        break;
      // 灰色
      case 4:
        colorText = 'font3';
        break;
      // 绿色
      case 5:
      case 9:
        colorText = 'font3';
        break;

    }
    return colorText;
  }

  // 上传文件夹字符串截取
  splitFileName(text: string) {
    var pattern: any = /\.{1}[a-z]{1,}$/;
    if (pattern.exec(text) !== null) {
      return (text.slice(0, pattern.exec(text).index));
    } else {
      return text;
    }
  }

  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在请求...', {nzDuration: 0}).messageId;
  }

  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }

  /**
   * 全局展示操作反馈信息
   * @param type 其他提示类型 success:成功 error:失败 warning：警告
   */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }

  // 对公转账一键复制
  transferInofoCopy() {
    let str = '';
    let tempArr = [
      {value: 'userName', label: '户名'},
      {value: 'bankName', label: '开户行'},
      {value: 'bankAccount', label: '账户'},
      {value: 'cnaps', label: '联行号'},
      {value: 'transferCode', label: '汇款识别码'}
    ];
    tempArr.forEach((item: any) => {
      str += item.label + '：' + this.transferInfo[item.value] + ';';
    });
    this.commonService.copyStr(str);
  }
}
